﻿using System;
using System.Collections.Generic;
using System.Linq;
using AwesomeSlider.Models;
using Orchard;
using Orchard.ContentManagement;
using Orchard.Core.Common.Models;
namespace AwesomeSlider.Services
{
public interface ISliderItemService : IDependency
    {
        SliderItemPart Create(SliderPart album);
        ContentItem Get(int id);
        ContentItem Get(int id, VersionOptions versionOptions);
        IEnumerable<SliderItemPart> Get(SliderPart sliderPart, VersionOptions versionOptions);
        IEnumerable<SliderItemPart> Get(SliderPart sliderPart, int skip, int count, VersionOptions versionOptions);
        int GetCount(SliderPart albumPart, VersionOptions versionOptions);
        void UpdateDescription(int id, string description);
        void Delete(SliderItemPart img);
    }

public class SliderItemService : ISliderItemService
{
    private readonly IContentManager _contentManager;

    public SliderItemService(IContentManager contentManager)
    {
        _contentManager = contentManager;
    }

    public SliderItemPart Create(SliderPart slider)
    {
        var sliderItem = _contentManager.New<SliderItemPart>("SliderItem");
        sliderItem.SliderPart = slider;
        return sliderItem;
    }

    public ContentItem Get(int id)
    {
        return Get(id, VersionOptions.Latest);
    }

    public ContentItem Get(int id, VersionOptions versionOptions)
    {
        return _contentManager.Get(id, versionOptions);
    }

    public IEnumerable<SliderItemPart> Get(SliderPart sliderPart, VersionOptions versionOptions)
    {
        return GetQuery(sliderPart, versionOptions).List().Select(ci => ci.As<SliderItemPart>());
    }

    public IEnumerable<SliderItemPart> Get(SliderPart sliderPart, int skip, int count, VersionOptions versionOptions)
    {
        return GetQuery(sliderPart, versionOptions).Slice(skip, count).ToList().Select(ci => ci.As<SliderItemPart>());
    }

    public int GetCount(SliderPart sliderPart, VersionOptions versionOptions)
    {
        return GetQuery(sliderPart, versionOptions).Count();
    }

    private IContentQuery<ContentItem, CommonPartRecord> GetQuery(ContentPart<SliderPartRecord> sliderPart, VersionOptions versionOptions)
    {
        return _contentManager.Query(versionOptions, "SliderItem").Join<CommonPartRecord>().Where(
                cr => cr.Container == sliderPart.Record.ContentItemRecord).OrderByDescending(cr => cr.CreatedUtc);
    }

    public void Delete(SliderItemPart sliderItem)
    {
        _contentManager.Remove(sliderItem.ContentItem);
    }


    public void UpdateDescription(int id,string description) {
        SliderItemPart sliderItem = Get(id).As<SliderItemPart>();
        sliderItem.Description = description;
    }
}
}